/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.tool;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;


/**
 * 备份工具类，提供数据导出到文本文件的功能。
 */
public class BackupUtils {
    private static final String TAG = "BackupUtils";
    private static BackupUtils sInstance; // 单例模式实例

    /**
     * 获取 BackupUtils 实例（单例模式）。
     *
     * @param context 应用上下文
     * @return BackupUtils 实例
     */
    public static synchronized BackupUtils getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new BackupUtils(context);
        }
        return sInstance;
    }

    /**
     * 备份或恢复状态的定义
     */

    public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD 卡未挂载
    public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在
    public static final int STATE_DATA_DESTROIED = 2; // 数据损坏
    public static final int STATE_SYSTEM_ERROR = 3; // 系统错误
    public static final int STATE_SUCCESS = 4; // 备份成功

    private TextExport mTextExport;

    /**
     * 私有构造方法，初始化 TextExport 实例。
     *
     * @param context 应用上下文
     */
    private BackupUtils(Context context) {
        mTextExport = new TextExport(context);
    }

    /**
     * 检查外部存储是否可用
     *
     * @return 如果 SD 卡已挂载，则返回 true；否则返回 false。
     */
    private static boolean externalStorageAvailable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 导出笔记到文本文件
     *
     * @return 备份状态码
     */
    public int exportToText() {
        return mTextExport.exportToText();
    }

    /**
     * 获取导出文本文件的文件名
     *
     * @return 文件名
     */
    public String getExportedTextFileName() {
        return mTextExport.mFileName;
    }

    /**
     * 获取导出文本文件的目录
     *
     * @return 文件目录
     */
    public String getExportedTextFileDir() {
        return mTextExport.mFileDirectory;
    }

    private static class TextExport {
        // 定义笔记表的查询字段
        private static final String[] NOTE_PROJECTION = {
                NoteColumns.ID,            // 笔记ID
                NoteColumns.MODIFIED_DATE, // 笔记最后修改日期
                NoteColumns.SNIPPET,       // 笔记摘要
                NoteColumns.TYPE           // 笔记类型
        };

        // 定义查询结果集中各字段的索引
        private static final int NOTE_COLUMN_ID = 0;
        private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
        private static final int NOTE_COLUMN_SNIPPET = 2;

        // 定义数据表的查询字段
        private static final String[] DATA_PROJECTION = {
                DataColumns.CONTENT,    // 数据内容
                DataColumns.MIME_TYPE,  // 数据MIME类型
                DataColumns.DATA1,      // 额外数据字段1（如通话日期）
                DataColumns.DATA2,      // 额外数据字段2
                DataColumns.DATA3,      // 额外数据字段3
                DataColumns.DATA4       // 额外数据字段4（如电话号码）
        };

        // 定义查询结果集中各字段的索引
        private static final int DATA_COLUMN_CONTENT = 0;
        private static final int DATA_COLUMN_MIME_TYPE = 1;
        private static final int DATA_COLUMN_CALL_DATE = 2;
        private static final int DATA_COLUMN_PHONE_NUMBER = 4;

        // 定义文本格式的数组，用于导出格式化文本
        private final String[] TEXT_FORMAT;
        // 文本格式索引
        private static final int FORMAT_FOLDER_NAME = 0;  // 目录名称格式
        private static final int FORMAT_NOTE_DATE = 1;    // 笔记日期格式
        private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式

        // 上下文对象
        private Context mContext;
        private String mFileName;      // 导出文件名
        private String mFileDirectory; // 导出文件目录

        // 构造方法，初始化上下文和格式化字符串
        public TextExport(Context context) {
            TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
            mContext = context;
            mFileName = "";
            mFileDirectory = "";
        }

        // 获取指定格式字符串
        private String getFormat(int id) {
            return TEXT_FORMAT[id];
        }

        /**
         * 导出指定文件夹内的笔记到文本文件
         */
        private void exportFolderToText(String folderId, PrintStream ps) {
            // 查询属于该文件夹的笔记
            Cursor notesCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_NOTE_URI,
                    NOTE_PROJECTION,
                    NoteColumns.PARENT_ID + "=?", new String[]{folderId}, null);

            if (notesCursor != null) {
                if (notesCursor.moveToFirst()) {
                    do {
                        // 输出笔记最后修改日期
                        ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
                                mContext.getString(R.string.format_datetime_mdhm),
                                notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));

                        // 获取笔记ID
                        String noteId = notesCursor.getString(NOTE_COLUMN_ID);
                        // 导出笔记内容
                        exportNoteToText(noteId, ps);
                    } while (notesCursor.moveToNext());
                }
                notesCursor.close(); // 关闭游标，释放资源
            }
        }

        /**
         * Export note identified by id to a print stream
         */
        private void exportNoteToText(String noteId, PrintStream ps) {
            // 查询数据库获取指定 noteId 的数据内容
            Cursor dataCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_DATA_URI, // 查询 URI
                    DATA_PROJECTION, // 查询的列
                    DataColumns.NOTE_ID + "=?", // 查询条件: 只获取指定 noteId 的数据
                    new String[]{noteId}, // 查询参数
                    null // 排序方式（此处不排序）
            );

            if (dataCursor != null) {
                if (dataCursor.moveToFirst()) { // 检查是否有数据
                    do {
                        // 获取数据的 MIME 类型
                        String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);

                        if (DataConstants.CALL_NOTE.equals(mimeType)) {
                            // 处理通话记录类型的笔记
                            String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); // 获取电话号码
                            long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); // 获取通话日期
                            String location = dataCursor.getString(DATA_COLUMN_CONTENT); // 获取通话附件位置

                            if (!TextUtils.isEmpty(phoneNumber)) {
                                // 如果电话号码不为空，则打印到文本流
                                ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
                            }
                            // 打印通话日期
                            ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
                                    .format(mContext.getString(R.string.format_datetime_mdhm), callDate)));

                            if (!TextUtils.isEmpty(location)) {
                                // 如果附件位置不为空，则打印到文本流
                                ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
                            }
                        } else if (DataConstants.NOTE.equals(mimeType)) {
                            // 处理普通文本类型的笔记
                            String content = dataCursor.getString(DATA_COLUMN_CONTENT);
                            if (!TextUtils.isEmpty(content)) {
                                ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
                            }
                        }
                    } while (dataCursor.moveToNext()); // 遍历所有数据
                }
                dataCursor.close(); // 关闭游标
            }

            // 在笔记之间打印分隔符
            try {
                ps.write(new byte[]{Character.LINE_SEPARATOR, Character.LETTER_NUMBER});
            } catch (IOException e) {
                Log.e(TAG, e.toString()); // 记录异常日志
            }
        }

        /**
         * 导出所有笔记到文本文件
         */
        public int exportToText() {
            if (!externalStorageAvailable()) {
                Log.d(TAG, "Media was not mounted");
                return STATE_SD_CARD_UNMOUONTED;
            }

            PrintStream ps = getExportToTextPrintStream();
            if (ps == null) {
                Log.e(TAG, "get print stream error");
                return STATE_SYSTEM_ERROR;
            }

            // 查询所有文件夹及其笔记
            Cursor folderCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_NOTE_URI,
                    NOTE_PROJECTION,
                    "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
                            + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
                            + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER,
                    null, null);

            if (folderCursor != null) {
                if (folderCursor.moveToFirst()) {
                    do {
                        String folderName = "";
                        if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
                            folderName = mContext.getString(R.string.call_record_folder_name);
                        } else {
                            folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
                        }
                        if (!TextUtils.isEmpty(folderName)) {
                            ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
                        }
                        String folderId = folderCursor.getString(NOTE_COLUMN_ID);
                        exportFolderToText(folderId, ps);
                    } while (folderCursor.moveToNext());
                }
                folderCursor.close();
            }

            // 导出根目录中的笔记
            Cursor noteCursor = mContext.getContentResolver().query(
                    Notes.CONTENT_NOTE_URI,
                    NOTE_PROJECTION,
                    NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0",
                    null, null);

            if (noteCursor != null) {
                if (noteCursor.moveToFirst()) {
                    do {
                        ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
                                mContext.getString(R.string.format_datetime_mdhm),
                                noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));

                        String noteId = noteCursor.getString(NOTE_COLUMN_ID);
                        exportNoteToText(noteId, ps);
                    } while (noteCursor.moveToNext());
                }
                noteCursor.close();
            }

            ps.close();
            return STATE_SUCCESS;
        }

        /**
         * 获取指向导出文本文件的 PrintStream
         */
        private PrintStream getExportToTextPrintStream() {
            File file = generateFileMountedOnSDcard(mContext, R.string.file_path, R.string.file_name_txt_format);
            if (file == null) {
                Log.e(TAG, "create file to exported failed");
                return null;
            }
            mFileName = file.getName();
            mFileDirectory = mContext.getString(R.string.file_path);
            PrintStream ps = null;
            try {
                FileOutputStream fos = new FileOutputStream(file);
                ps = new PrintStream(fos);
            } catch (FileNotFoundException | NullPointerException e) {
                e.printStackTrace();
                return null;
            }
            return ps;
        }
    }


    /**
     * 生成用于存储导出数据的文本文件
     */
    private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
        StringBuilder sb = new StringBuilder();
        sb.append(Environment.getExternalStorageDirectory());
        sb.append(context.getString(filePathResId));
        File filedir = new File(sb.toString());
        sb.append(context.getString(
                fileNameFormatResId,
                DateFormat.format(context.getString(R.string.format_date_ymd),
                        System.currentTimeMillis())));
        File file = new File(sb.toString());

        try {
            if (!filedir.exists()) {
                filedir.mkdir();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            return file;
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
